package cn.jolyoulu.mqtt.service.impl;

import cn.jolyoulu.mqtt.entity.dto.MqttHeartBeatMsgDTO;
import cn.jolyoulu.mqtt.entity.dto.MqttMsgDTO;
import cn.jolyoulu.mqtt.entity.dto.MqttMsgType;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Service;
import cn.jolyoulu.mqtt.service.MqttSubTopicService;

import java.util.Objects;

@Slf4j
@Service
public class MqttSubTopicServiceImpl implements MqttSubTopicService {

    @Override
    public void callBack(String topic, MqttMessage message) {
        String jsonString = new String(message.getPayload());
        log.info("接收消息主题:" + topic);
        log.info("接收消息内容:" + jsonString);
        MqttMsgType msgType = MqttMsgDTO.getJPushMsgType(jsonString);
        if (Objects.nonNull(msgType)){ //处理消息
            switch (msgType){
                case HEART_BEAT:
                    MqttMsgDTO<MqttHeartBeatMsgDTO> hbMsg = JSONObject.parseObject(jsonString, new TypeReference<MqttMsgDTO<MqttHeartBeatMsgDTO>>() {});
                    this.saveHeartBeatInfo(hbMsg);
                    break;
                case LAST_WILL:
                    //遗嘱消息和预想的结果不一样，他是断网后重连才会被发送
//                    MqttMsgDTO<MqttLastWillMsgDTO> lastWillMsg = JSONObject.parseObject(jsonString, new TypeReference<MqttMsgDTO<MqttLastWillMsgDTO>>() {});
//                    this.lostConnection(lastWillMsg);
                    break;
                default:
                    log.error("接收消息，但未处理:" + jsonString);
                    break;
            }
        }
    }

    @Override
    public void saveHeartBeatInfo(MqttMsgDTO<MqttHeartBeatMsgDTO> hbMsg) {
        MqttHeartBeatMsgDTO content = hbMsg.getContent();
    }
}
